
//添加遮罩层
document.write('<div id="son51-body-loading" class="son51-body-loading"><p class="son51-loading"><i class="icon-spinner icon-spin icon-2x"></i><span class="son51-loading-txt">正在加载,请稍后...</span></p></div>');

//获取51son.js当前目录
var js=document.scripts;
var son_js = "";
for(var i=js.length;i>0;i--){
	if(js[i-1].src.indexOf("51son.js")>-1){
		son_js=js[i-1].src.substring(0,js[i-1].src.lastIndexOf("/")+1);
	}
	if(js[i-1].src.indexOf("51son.min.js")>-1){
		son_js=js[i-1].src.substring(0,js[i-1].src.lastIndexOf("/")+1);
	}
}

//加载其他的js文件
document.write("<script src='"+son_js+"jquery-1.9.1.min.js'></script>");
document.write("<script src='"+son_js+"bootstrap.min.js'></script>");
document.write("<script src='"+son_js+"jquery.cookie.js'></script>");
document.write("<script src='"+son_js+"jsencrypt.js'></script>");
document.write("<script src='"+son_js+"template.js'></script>");

//定义模板加载完成事件
var template_load = [];

//自定义jquery类
var vjs = function(){

	//公钥
	var RSA_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTSJnTn3Wk30DTtBaPcsNgLOHC1hXv4ygV8ooo2C4VN6zbY0cEpD0z+Yu6XOFDduBLwYrvrHdO+RKFz2NX+8hAfEkYi1v5Ngye0gKBavY9gqva5lcSKiSQcP2pEk+wuC+1etOGePz+lG72BZ1Aaj7yQU3DSzZ6Jw3f9a6tvrIFEQIDAQAB";

	//设置请求表头
	var setHeader = function(request){
		return request;
	};

	//自定义遮罩层
	var maskOpen = function(){
		var maskId = "son51-mask_" + parseInt(100000*Math.random());
		var $mask = $("<div>").addClass("son51-mask").attr("id", maskId);
		var $loading = $("<span>").addClass("icon-spinner icon-spin icon-2x son51-loading");
		$mask.append($loading);
		$("body").append($mask);
		return maskId;
	};

	var maskClose = function(maskId){
		$("#"+maskId).remove();
	};

	return{
		//自定义ajax请求
		ajax:function(ajx){
			if(!ajx.url){
				console.log("缺少url参数");
				return false;
			}
			if(!ajx.type){
				ajx.type="post";
			}
			if(!ajx.dataType){
				ajx.dataType = "json";
			}
			if(ajx.async==undefined){
				ajx.async = true;
			}

			//遮罩层id
			var maskId = null;

			$.ajax({
				url:ajx.url,
				type:ajx.type,
				data:ajx.data?ajx.data:{},
						dataType:ajx.dataType,
						async:ajx.async,
						beforeSend: function(request) {
							request = setHeader(request);
							if(!ajx.async){
								maskId = maskOpen();
							}
						},
						success:function(data){
							if(!ajx.async){
								maskClose(maskId);
							}
							if(ajx.success){
								ajx.success(data);
							}
						},
						error: function(XMLHttpRequest, textStatus, errorThrown){
							if(!ajx.async){
								maskClose(maskId);
							}
							if(ajx.error){
								ajx.error(XMLHttpRequest, textStatus, errorThrown);
							}
						}
			});
		},

		//获取url请求参数
		getUrlParam:function(url, name){
			if(url.indexOf("?")>0){
				url = url.substr(url.indexOf("?")+1);
				var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
				var r = url.match(reg);
				if(r!=null)return  decodeURI(r[2]); return null;
			}
			else{
				return null;
			}
		},

		//rsa加密
		encrypt: function(str) {
			var encrypt = new JSEncrypt();
			encrypt.setPublicKey(RSA_PUBLIC_KEY);
			var encrypted = encrypt.encrypt(str);
			return encrypted;
		},

		//模板,基于template.js，用于同一渲染和加载
		template:function(){
			var temps = $("[data-template]");
			$.each(temps ,function(i,o){
				var temp = $(o).attr("data-template");
				var data = $(o).attr("data-object");
				var url = $(o).attr("data-url");
				if(url){
					vjs.ajax({//分装的ajax请求
						url:$(o).attr("data-url"),
						type:!$(o).attr("data-method")?"get":$(o).attr("data-method"),
								dataType:!$(o).attr("data-type")?"json":$(o).attr("data-type"),
										data:!$(o).attr("data-params")?{}:eval("("+$(o).attr("data-params")+")"),
												async:!$(o).attr("data-async")?false:($(o).attr("data-params")=="true"?true:false),
														success:function(result){
															var t = $("script[id='"+temp+"']");
															if(!t || t.length == 0){
																$(o).load(temp+".html", function( response, status, xhr ) {
																	temp = temp.substr(temp.lastIndexOf("/")+1);
																	var html = template(temp, result);
																	$(o).append(html);
																	$("script[id='"+temp+"']").remove();
																	vjs.loadtemplate();
																});
															}
															else{
																var html = template(temp, result);
																$(o).append(html);
																$("script[id='"+temp+"']").remove();
																vjs.loadtemplate();
															}
														}
					});
				}
				else{
					var t = "";
					try{
						 t = $("script[id='"+temp+"']");
					}
					catch(exception){}
					
					if(!t || t.length == 0){
						$(o).load(temp+".html", function( response, status, xhr ) {
							temp = temp.substr(temp.lastIndexOf("/")+1);
							var html = template(temp, data?eval(data):{});
							$(o).append(html);
							$("script[id='"+temp+"']").remove();
							vjs.loadtemplate();
						});
					}
					else{
						var html = template(temp, data?eval(data):{});
						$(o).append(html);
						$("script[id='"+temp+"']").remove();
						vjs.loadtemplate();
					}
				}
			});
		},

		//修改可访问外部文件
		templated:function($container, temp, data, callback){
			var t = "";
			try{
				 t = $("script[id='"+temp+"']");
			}
			catch(exception){}
			if(!t || t.length == 0){
				$container.load(temp+".html", function( response, status, xhr ) {
					temp = temp.substr(temp.lastIndexOf("/")+1);
					var html = template(temp, data);
					$container.append(html);
					$("script[id='"+temp+"']").remove();
					vjs.loadtemplate();
					if(callback){
						callback();
					}
				});
			}
			else{
				var html = template(temp, data);
				$container.append(html);
				$("script[id='"+temp+"']").remove();
				vjs.loadtemplate();
				if(callback){
					callback();
				}
			}
		},

		//提示框
		alert: function(str, callback, temp){
			if(!temp){
				temp = son_js+"common/alert-template";
			}
			var maskId = maskOpen();
			$("#"+maskId).find(".son51-loading").remove();
			var alertId = "son51-alert_" + parseInt(100000*Math.random());
			var data = {
					title: str,
					alertId: alertId,
			};
			var alert = $("<div>").addClass("son51-alert").attr("id", alertId);
			vjs.templated(alert, temp, data);
			$("body").append(alert);
			$(document).on("click", "[alertId='"+alertId+"']", function(){
				maskClose(maskId);
				$("#"+alertId).remove();
				if(callback){
					callback();
				}
				return false;
			});
		},

		//确认框
		confirm: function(str, certainback, cancelback, temp){
			if(!temp){
				temp = son_js+"common/confirm-template";
			}
			var maskId = maskOpen();
			$("#"+maskId).find(".son51-loading").remove();
			var confirmId = "son51-confirm_" + parseInt(100000*Math.random());
			var data = {
					title: str,
					confirmId: confirmId,
			};
			var confirm = $("<div>").addClass("son51-confirm").attr("id", confirmId);
			vjs.templated(confirm, temp, data);
			$("body").append(confirm);
			$(document).on("click", "[confirm-cancel='"+confirmId+"']", function(){
				maskClose(maskId);
				$("#"+confirmId).remove();
				if(cancelback){
					cancelback();
				}
				return false;
			});
			$(document).on("click", "[confirm-certain='"+confirmId+"']", function(){
				maskClose(maskId);
				$("#"+confirmId).remove();
				if(certainback){
					certainback();
				}
				return false;
			});
		},

		//加载窗体
		dialog: function(temp, title, data, callback){
			if(!temp){
				vjs.alert("请添加窗体模板...");
				return false;
			}
			var maskId = maskOpen();
			$("#"+maskId).find(".son51-loading").remove();
			var dialogId = "son51-dialog_" + parseInt(100000*Math.random());
			if(!data){
				data = new Object();
			}
			data.dialogId = dialogId;
			var dialog = $("<div>").addClass("son51-dialog").attr("id", dialogId);
			var cont = $("<div>").addClass("son51-popup-content");
			var header = $("<div>").addClass("son51-dialog-header").text(title);
			var span = $("<span>").addClass("son51-dialog-close").html("&times;");
			var body = $("<div>").addClass("son51-dialog-body clearfix");
			header.append(span);
			cont.append(header).append(body);
			dialog.append(cont);
			vjs.templated(body, temp, data);
			$("body").append(dialog);
			span.on("click", function(){
				maskClose(maskId);
				if(callback){
					callback();
				}
				$("#"+dialogId).remove();
			});
		},
		//load事件
		onload:function(callback){
			var func = window.onload;
			if(typeof window.onload!='function'){ 
				if(callback){
					window.onload=callback; 
				}
			}else{ 
				window.onload=function(){ 
					func(); 
					if(callback){
						callback();
					}
				};
			} 
		},
		//添加渲染事件
		templateload:function(callback){
			template_load.push(callback);
		},
		//渲染完成
		loadtemplate:function(){
			var queue = new Array();
			queue = template_load.concat();
			template_load.length = 0;
			$.each(queue, function(i,o){
				if(o){
					o();
				}
			});
			queue.length = 0;
		},
		//上传
		upload:function(form, file, callback){
			var id = parseInt(100000*Math.random());
			var ifr = $("<iframe>").attr("name", "ifr_"+id).css("display","none");
			$("#"+form).attr("target", ifr.attr("name"));
			$("body").append(ifr);
			ifr.load(function(){
				var result = ifr.contents().find("pre").text();
				if(callback){
					callback(eval("("+result+")"));
				}
			});
			$("body").on("change", "#"+file, function(){
				if(!$("#"+form).attr("target")){
					$("#"+form).attr("target", ifr.attr("name"));
				}
				$("#"+form).submit();
			});
		},
		
	};
}();

vjs.onload(function(){
	//加载并渲染模板
	vjs.template();
	//关闭遮罩
	setTimeout(function(){
		if(document.getElementById("son51-body-loading")){
			document.getElementById("son51-body-loading").remove();
		}
	},500);
});

//别名
var $$ = vjs;


